package persentation.presentTeacher;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import persentation.presentStudent.ExceptionHandler;
import dataservice.ResultMessage;
import vo.chooseCourseVO.ChooseCourseVO;
import vo.userVO.StudentVO;
import businesslogic.chooseCourseBl.ChooseCourseController;
import businesslogic.courseBl.CourseController;

import java.io.*;

import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class FillScorePanel extends JPanel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTable table;
	private String fileName;
	private MyTabbedPane tabbedPane;
	private JScrollPane scrollPane;
	private JButton okButton;
	private JButton noButton;
	private ArrayList<StudentVO> studentList;
	private ArrayList<ChooseCourseVO> chooseCourseList=new ArrayList<>();
	private String userID;
	private ArrayList<ResultMessage> resultMessageList=new ArrayList<>();
	private ChooseCourseController chooseCourseController;
	
	
	
	public FillScorePanel(ChooseCourseController chooseCourseController,final String courseID) {
		
		this.chooseCourseController=chooseCourseController;
		try {
			studentList=chooseCourseController.getStuList(courseID);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			ExceptionHandler.networkException();
		}
		
		System.out.println(studentList.size()+"Size");
		
		
		
		new CourseController(userID);
		
		for(StudentVO student:studentList){
		
			ChooseCourseController chooseController=new ChooseCourseController(student.getId());
			ArrayList<ChooseCourseVO> arrayListTemp;
			try {
				arrayListTemp = chooseController.getAllChooseCourseRecord();
				System.out.println(arrayListTemp.size()+"zzz");
				for(ChooseCourseVO choosecourse:arrayListTemp){
					if(choosecourse.getCourseId().equals(courseID))
						chooseCourseList.add(choosecourse);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
				ExceptionHandler.networkException();
			}
		}
		
		
		
		System.out.println(chooseCourseList.size()+"lll");
		
		
		
		
		setSize(800,600);
		setLayout(null);
		
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 10, 780, 404);
		this.add(scrollPane);
		
	    
		
		
		
		
		table = new JTable(){

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			
	            
		};
		table.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		table.setModel(new DefaultTableModel(
			new Object[][] {
				
			},
			new String[] {
				"学生编号", "学生姓名", "所在院系", "课程成绩"
			}
		) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			Class[] columnTypes = new Class[] {
				Object.class, Object.class, Object.class, Double.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
			
			public boolean isCellEditable(int row, int column)
			{
				
				if(column==3)
					return true;
				return false;
			}
		});
		table.setBounds(119, 424, 262, 143);
		scrollPane.setViewportView(table);
		table.setForeground(new Color(0, 0, 0));
		table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
	
		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		table.add(table.getTableHeader());
		fillTable();
		
		okButton=new JButton("确    认");
		okButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
			
				ResultMessage message=sendRequest();
				if(message==ResultMessage.UPDATE_SUCCESS)
					JOptionPane.showMessageDialog(null,"登记成绩成功！","提示",JOptionPane.INFORMATION_MESSAGE);
				else
					JOptionPane.showMessageDialog(null,"登记成绩失败！","提示",JOptionPane.INFORMATION_MESSAGE);
				
			}
		});
		
		okButton.setBounds(61, 456, 122, 47);
		
		okButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		add(okButton);
		
		
		
		noButton=new JButton("取    消");
		noButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				fillTable();
			}
		});
		
		noButton.setBounds(614, 456, 116, 47);
		
		noButton.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		add(noButton);
		
		JButton button = new JButton("导    入");
		button.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
		
				final JFileChooser jFileChooser=new JFileChooser();
				
				jFileChooser.setFileFilter(new FileFilter() {
					
					@Override
					public String getDescription() {
						// TODO Auto-generated method stub
						return null;
					}
					
					@Override
					public boolean accept(File f) {
						return f.getName().endsWith(".xls");
					}
				});
				
				int retVal=jFileChooser.showOpenDialog(null);
				jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				if(retVal==JFileChooser.APPROVE_OPTION){
					
					File file=jFileChooser.getSelectedFile();
				
					
						try {
							Workbook workbook=Workbook.getWorkbook(file);
							Sheet sheet=workbook.getSheet(0);
							
							for(int i=0;i<sheet.getRows();i++){
								double score;
								
								if(sheet.getCell(3,i)==null)
									score=0;
								else {
									Cell cell=sheet.getCell(3,i);
									
									score=Double.parseDouble(cell.getContents());
								}
								

							
								table.setValueAt(score, i, 3);
								
							}
							JOptionPane.showMessageDialog(null,"成绩导入成功！","提示",JOptionPane.INFORMATION_MESSAGE);

							workbook.close();	
						} catch (BiffException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					
					
						
				}
				jFileChooser.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						
						
					}
				});
			}
		});
		button.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		button.setBounds(251, 456, 116, 47);
		add(button);
		
		JButton button_1 = new JButton("导    出");
		button_1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					String path=null;
					JFileChooser fc = new JFileChooser(); 
					fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					 int intRetVal = fc.showOpenDialog(null); 
				      if( intRetVal == JFileChooser.APPROVE_OPTION){ 
				        path=fc.getSelectedFile().getPath(); 
				      } 
					
				     
				      
				      
					
					
					WritableWorkbook workbook=Workbook.createWorkbook(new File(path+"\\"+fileName+" 课程成绩.xls"));
					WritableSheet sheet=workbook.createSheet("第一页",0); 
					for(int i=0;i<table.getRowCount();i++){
						jxl.write.Label id=new jxl.write.Label(0,i,table.getValueAt(i, 0).toString());
						jxl.write.Label name=new jxl.write.Label(1,i,table.getValueAt(i, 1).toString());
						jxl.write.Label depart=new jxl.write.Label(2,i,table.getValueAt(i, 2).toString());
						jxl.write.Number score=new jxl.write.Number(3,i,Double.parseDouble(table.getValueAt(i, 3).toString()));
						sheet.addCell(id);
						sheet.addCell(name);
						sheet.addCell(depart);
						sheet.addCell(score);
					}
					
					workbook.write();
					workbook.close();
					JOptionPane.showMessageDialog(null,"成绩导出成功！请到 "+path+" 目录下查找"+fileName +"课程成绩xls文件。","提示",JOptionPane.INFORMATION_MESSAGE);
				} catch (Exception e2) {
					e2.printStackTrace();
					JOptionPane.showMessageDialog(null,"成绩导出失败！","提示",JOptionPane.INFORMATION_MESSAGE);
				}
				
			}
		});
		button_1.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		button_1.setBounds(438, 456, 116, 47);
		add(button_1);
		


	}
	
	
		
		
	public void fillTable(){
		DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
		 tableModel.setRowCount(0);
		 int i=0;
		 for(ChooseCourseVO chooseCourse:chooseCourseList){
			 Object[] array=new Object [4];
			 array[0]=(String)chooseCourse.getStudentId();
			 System.out.println(array[0]);
			
			 array[1]=(String)chooseCourse.getStudentName();
			
			 array[2]=(String)studentList.get(i).getDepartmentId();
			 i++;
			 array[3]=(Double)chooseCourse.getScore();
			
			
	 		
			 
			 
			 tableModel.addRow(array);
			 table.invalidate();
			 table.updateUI();
	      }
	} 
	
	public ResultMessage sendRequest(){
		
		ResultMessage msg=null;
		
		for(int i=0;i<chooseCourseList.size();i++){
			double score=(double)table.getValueAt(i, 3);
			ResultMessage resultMessage;
			try {
				resultMessage = chooseCourseController.setScore(chooseCourseList.get(i), score);
		
				resultMessageList.add(resultMessage);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				ExceptionHandler.networkException();
			}
			
		}
		
		for(ResultMessage resultMessage:resultMessageList){
			if(resultMessage==ResultMessage.UPDATE_FAILURE)
				msg=ResultMessage.UPDATE_FAILURE;
			
			else {
				msg=ResultMessage.UPDATE_SUCCESS;
			}
		}
		
		
		return msg;
	}
	
	public void setTabbedPane(MyTabbedPane tabbedPane){
		this.tabbedPane=tabbedPane;
	}
	
	public void setFileName(String fileName){
		this.fileName=fileName;
	}
	
	public void setUserID(String userID){
		this.userID=userID;
	}
}
